#import "MOSendCodeButton.h"

@interface MOSendCodeButton ()

@property (nonatomic, strong) dispatch_source_t timer;  // 让 _timer 成为实例变量

@end

@implementation MOSendCodeButton

- (void)jk_startTime:(NSInteger)timeout title:(NSString *)tittle waitTittle:(NSString *)waitTittle {
    [self jk_stopTimer]; // 先销毁旧的 timer，防止重复创建

    __block NSInteger timeOut = timeout;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(self.timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);

    dispatch_source_set_event_handler(self.timer, ^{
        if (timeOut <= 0) {
            [self jk_stopTimer]; // 倒计时结束，销毁 Timer
            dispatch_async(dispatch_get_main_queue(), ^{
                [self setTitle:tittle forState:UIControlStateNormal];
                self.enabled = YES;
            });
        } else {
            int seconds = timeOut % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"____%@",strTime);
                [self setTitle:[NSString stringWithFormat:@"%@ %@", waitTittle, strTime] forState:UIControlStateNormal];
                self.enabled = NO;
            });
            timeOut--;
        }
    });
    dispatch_resume(self.timer);
}

// ** 新增手动销毁方法**
- (void)jk_stopTimer {
    if (self.timer) {
        dispatch_source_cancel(self.timer);
        self.timer = nil;
    }
}

// ** 在 dealloc 里销毁 timer**
- (void)dealloc {
    [self jk_stopTimer];
}

@end
